package com.cdsxt.util;

import java.lang.reflect.Field;

import org.springframework.beans.BeanUtils;

public class BeanUtil {
	
	public static void main(String[] args)throws Exception {
//		UserPo up=new UserPo();
//		up.setId(11);
//		up.setUsername("zzz");
//		UserPo up2=new UserPo();
//		up2.setBrithday(new Date());
//		up2.setUsername("xxxx");
//
//		System.out.println(up);
//		System.out.println(up2);
//		copyBeanNotNullProperties(up, up2);
//		System.out.println(up2);
//		
//		System.out.println(Arrays.toString(up.getClass().getSuperclass().getDeclaredFields()));
//		System.out.println(up.getClass().getDeclaredField("id"));
		
		
	}
	/**
	 * copy非null值的bean的属性（不包含父类）
	 * ps：注意不会copy src里父类的属性,可以参考（src.getClass().getSuperclass()）
	 * @param src
	 * @param target
	 */
	public static void copyBeanNotNullProperties(Object src, Object target) {
		Class<? extends Object> curCls = src.getClass();
		copyBeanNotNullPropertiesCustomCls(src, target, curCls);
	}
	/**
	 * copy非null值的bean的属性(包含1个父类)
	 * ps：注意不会copy src里父类的属性,可以参考（src.getClass().getSuperclass()）
	 * @param src
	 * @param target
	 */
	public static void copyBeanNotNullProperties2(Object src, Object target) {
		Class<? extends Object> curCls = src.getClass();
		Class<? extends Object> curClsParent = curCls.getSuperclass();
		copyBeanNotNullPropertiesCustomCls(src, target, curCls);
		copyBeanNotNullPropertiesCustomCls(src, target, curClsParent);
	}
	/**
	 * copy非null值的bean的属性(指定类customCls的属性被复制)
	 * ps：注意不会copy src里父类的属性,可以参考（src.getClass().getSuperclass()）
	 * @param src
	 * @param target
	 * @param customCls 指定的被复制的类
	 */
	//
	public static void copyBeanNotNullPropertiesCustomCls(Object src, Object target,Class customCls) {
		try {
			Field [] fieldArr  = customCls.getDeclaredFields();
			for (Field field : fieldArr) {
				field.setAccessible(true);
				Object fieldVal=field.get(src);
				//不为null，则copy
				if (fieldVal!=null) {
					//Field targetField = curCls.getDeclaredField(srcField.getName());
					//targetField.setAccessible(true);
					field.set(target, fieldVal);
				}
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	
	/**
	 * copy自定义（可以排除一部分属性）的bean的属性
	 * @param src
	 * @param target
	 */
	public static void copyBeanCustomProperties(Object src, Object target,String[] ignoreProperties) {
		BeanUtils.copyProperties(src, target, ignoreProperties);
	}
	/**
	 * copy所有的bean的属性
	 * @param src
	 * @param target
	 */
	public static void copyBeanAllProperties(Object src, Object target) {
		BeanUtils.copyProperties(src, target);
	}
	
}
